package cn.t.service.user;


import cn.t.core.enums.base.BaseStatusEnum;
import cn.t.core.exception.BizException;
import cn.t.core.service.ServiceImpl;
import cn.t.core.enums.base.CommonError;
import cn.t.model.user.ScenarioInfoDO;
import cn.t.repository.user.ScenarioInfoRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.t.constants.Constants.REDIS_KEY__SCENARIO_INFO;


/**
 * 场景信息表领域服务
 * @author l
 */
@Slf4j
@Service
@AllArgsConstructor
public class ScenarioInfoService extends ServiceImpl<ScenarioInfoDO, ScenarioInfoRepository> {

    public ScenarioInfoDO findByCode(String scenarioCode) {
        String redisKey = String.format(REDIS_KEY__SCENARIO_INFO, scenarioCode);
        ScenarioInfoDO result = (ScenarioInfoDO) redissonClient.getBucket(redisKey).get();
        if (result != null && result.getScenarioCode() != null && result.getScenarioCode().equals(scenarioCode)) {
            return result;
        }

        ScenarioInfoDO template = new ScenarioInfoDO();
        template.setScenarioCode(scenarioCode);
        template.setScenarioStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));

        List<ScenarioInfoDO> results = repository.findByModel(template, 0, 1, null, null);
        if (results == null || results.isEmpty()) {
            log.warn("场景不存在，场景编码：{}", scenarioCode);
            throw new BizException(CommonError.BIZ_EXCEPTION, "场景不存在");
        }

        redissonClient.getBucket(redisKey).set(results.get(0), 1, TimeUnit.HOURS);

        return results.get(0);
    }

    @Autowired
    private RedissonClient redissonClient;
}
